package com.tcwlkj.uuService.ui.login;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.util.ArraySet;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.tcwlkj.uuService.MainActivity;
import com.tcwlkj.uuService.MyApp;
import com.tcwlkj.uuService.NetWork.HttpCallBack;
import com.tcwlkj.uuService.NetWork.RetrofitUtils;
import com.tcwlkj.uuService.R;
import com.tcwlkj.uuService.model.AddressModel;
import com.tcwlkj.uuService.model.CommonResponse;
import com.tcwlkj.uuService.model.DeviceModle;
import com.tcwlkj.uuService.model.LocationModel;
import com.tcwlkj.uuService.model.LoginModel;
import com.tcwlkj.uuService.model.VerificationCodeModel;
import com.tcwlkj.uuService.ui.BaseActivity;
import com.tcwlkj.uuService.ui.UserXieYi;
import com.tcwlkj.uuService.utils.Const;
import com.tcwlkj.uuService.utils.PreferencesUtils;
import com.tcwlkj.uuService.utils.TimeCount;
import com.tcwlkj.uuService.utils.ToastUtil;
import com.tcwlkj.uuService.utils.Tools;
import com.tcwlkj.uuService.widget.SmoothCheckBox;

import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/10/9 0009.
 * 注册界面
 */

public class RegisterActivity extends BaseActivity implements TextWatcher {
    @Bind(R.id.edit_phone_reg)
    EditText editPhoneReg;
    @Bind(R.id.tv_cityname_reg)
    TextView tv_cityname;
    @Bind(R.id.btn_submit_reg)
    Button btn_submit;
    @Bind(R.id.edit_checknum_reg)
    EditText edit_checknum;
    @Bind(R.id.edit_ps_reg)
    EditText edit_ps;
    @Bind(R.id.btn_send_reg)
    TextView btn_send;
    @Bind(R.id.check_isallow_reg)
    SmoothCheckBox checkIsallowReg;
    @Bind(R.id.iv_visible)
    ImageView iv_visible;

    private int jpush;

    private LocationModel locationModel=new LocationModel(0d,0d);
    private TimeCount time;
    private LocationClient mLocationClient;//定位的客户端
    private MyLocationListener mMyLocationListener;//定位的监听器
    private volatile boolean isFristLocation = true;//是否是第一次定位
    /**
     * 最新一次的经纬度
     */
    private double mCurrentLantitude;
    private double mCurrentLongitude;


    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Set<String> tag = new ArraySet<String>();
            tag.add("330100");
            tag.add("杭州市");
            JPushInterface.setAliasAndTags(RegisterActivity.this,"SD" +PreferencesUtils.getString(RegisterActivity.this,"userID")+jpush,tag,mAliasCallback);

//            JPushInterface.setAlias(RegisterActivity.this, "SD" +PreferencesUtils.getString(RegisterActivity.this,"userID")+jpush, mAliasCallback);
//            Set<String> tag = new ArraySet<String>();
//            tag.add("330100");
//            tag.add("杭州市");
//            JPushInterface.setTags(RegisterActivity.this, tag, mAliasCallback);
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registered);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        changeTitle("立即注册");
        time = new TimeCount(baseContext, 60000, 1000, btn_send);
        edit_checknum.addTextChangedListener(this);
        edit_ps.addTextChangedListener(this);
        tv_cityname.addTextChangedListener(this);
        editPhoneReg.addTextChangedListener(this);
        checkIsallowReg.setChecked(true);
        btn_submit.setBackgroundResource(R.drawable.bg_btn_gray);
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                isFristLocation = true;
                initMyLocation();
            }
        }, R.string.address, Manifest.permission.ACCESS_FINE_LOCATION);
    }

    boolean visible=true;
    @OnClick({R.id.btn_send_reg, R.id.re_location, R.id.btn_submit_reg, R.id.tv_register_xieyi,R.id.iv_visible})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_send_reg://获取验证码
                getcode();//获取验证码
                break;
            case R.id.re_location://定位
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        isFristLocation = true;
                        initMyLocation();
                    }
                }, R.string.address, Manifest.permission.ACCESS_FINE_LOCATION);
                break;
            case R.id.btn_submit_reg://提交注册
                Register();//注册
                break;
            case R.id.tv_register_xieyi://服务条款
                Intent intent = new Intent(baseContext, UserXieYi.class);
                intent.putExtra("XIEYI_TYPE", "TC-ZCXY-PN002");
                startActivity(intent);
                break;
            case R.id.iv_visible:
                if(visible){
                    iv_visible.setImageDrawable(getResources().getDrawable(R.mipmap.visible));
                    visible=false;
                    edit_ps.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }else {
                    iv_visible.setImageDrawable(getResources().getDrawable(R.mipmap.invisible));
                    visible=true;
                    edit_ps.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                break;
        }
    }

    public void getcode() {
        String str_phone = editPhoneReg.getText().toString().trim();
        if (TextUtils.isEmpty(str_phone)) {
            ToastUtil.getInstance().show("请先输入手机号");
            return;
        } else {
            if (!Tools.isMobileNumber(str_phone)) {
                ToastUtil.getInstance().show("电话号码格式不正确！");
                return;
            }
        }
        Call<CommonResponse<VerificationCodeModel>> httpResultCall = RetrofitUtils.getRequest(this, false).getcode( str_phone, "113,0,3");
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<VerificationCodeModel>>() {
            @Override
            public void onSuccess(Object t) {
                CommonResponse<VerificationCodeModel> commonResponse= (CommonResponse<VerificationCodeModel>) t;
                btn_send.setClickable(false);
                time.start();
            }
            @Override
            public void onFail(int code, String message) {
                if(code == 40104||code==40102||code==40100){
                   getcode();
                }else {
                    ToastUtil.getInstance().show(message);
                }
            }
        });
    }//获取验证码

    public void Register() {
        String phone = editPhoneReg.getText().toString().trim();
        String yzm = edit_checknum.getText().toString().trim();
        String pwd = edit_ps.getText().toString().trim();
        String city = tv_cityname.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            ToastUtil.getInstance().show("请输入手机号码");
            return;
        }
        if (!Tools.isMobileNumber(phone)) {
            ToastUtil.getInstance().show("手机号格式不正确");
            return;
        }
        if (yzm.length() < 4 || yzm.length() > 6) {
            ToastUtil.getInstance().show("验证码格式不正确");
            return;
        }
        if (pwd.length() < 6) {
            ToastUtil.getInstance().show("密码长度不少于6位");
            return;
        }
        if(pwd.length()>20){
            ToastUtil.getInstance().show("密码长度不大于20位");
            return;
        }
        if (Tools.isContainChinese(pwd)) {
            ToastUtil.getInstance().show("密码不能包含汉字,请重新输入");
            return;
        }
        if (!checkIsallowReg.isChecked()) {
            ToastUtil.getInstance().show("请选择接受服务条款");
            return;
        }
        DeviceModle deviceModle = new DeviceModle("0", Tools.getDeviceModel(), Tools.getDeviceSystemVersion(), Tools.getVersion(baseContext), Tools.getIPAddress(baseContext), Tools.isNotificationEnabled(baseContext), Tools.getLocalMacAddressFromIp(baseContext), Tools.isLocationEnabled(baseContext));

        Call<CommonResponse<LoginModel>> httpResultCall = RetrofitUtils.getRequest(this, true).Register("driver", phone, pwd, yzm, Tools.javabeanToJson(locationModel), Tools.javabeanToJson(deviceModle));
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<LoginModel>>() {
            @Override
            public void onSuccess(Object t) {
                CommonResponse<LoginModel> commonResponse= (CommonResponse<LoginModel>) t;
                PreferencesUtils.putString(MyApp.getContext(),"userID",commonResponse.getData().getUserID()+"");
                PreferencesUtils.putString(MyApp.getContext(),"openid",commonResponse.getData().getOpenID()+"");
                PreferencesUtils.putString(MyApp.getContext(),"token",commonResponse.getData().getToken()+"");
                PreferencesUtils.putString(MyApp.getContext(),"JPushID",commonResponse.getData().getJPushID());
                PreferencesUtils.putBoolean(MyApp.getContext(),"Login",true);

                jpush = (int) (Math.random() * 1000);
                if (JPushInterface.isPushStopped(RegisterActivity.this)) {
                    JPushInterface.resumePush(RegisterActivity.this);
                }

                Set<String> tag = new ArraySet<String>();
                tag.add("330100");
                tag.add("杭州市");
                JPushInterface.setAliasAndTags(RegisterActivity.this,"SD" + commonResponse.getData().getUserID()+ jpush,tag,mAliasCallback);

//                JPushInterface.setAlias(RegisterActivity.this, "SD" + commonResponse.getData().getUserID()+ jpush, mAliasCallback);
//                Set<String> tag = new ArraySet<String>();
//                tag.add("330100");
//                tag.add("杭州市");
//                JPushInterface.setTags(RegisterActivity.this, tag, mAliasCallback);

                startActivity(MainActivity.class);
                finish();
                Const.login.finish();
            }
            @Override
            public void onFail(int code, String message) {
                if(code == 40104||code==40102||code==40100){
                    Register();
                }else {
                    ToastUtil.getInstance().show(message);
                }
            }
        });
    }//注册

    //    在JPush服务stop状态下设置了tag或alias（6012）
    TagAliasCallback mAliasCallback = new TagAliasCallback() {
        public String logs;
        @Override
        public void gotResult(int code, String s, Set<String> set) {
            switch (code) {
                case 0://极光设置别名成功
                    SubmitJPushID();//提交极光ID
                    break;
                case 6002:
                default:
                    mHandler.sendEmptyMessageDelayed(1,6000);
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    System.out.println("===========>>>logs:" + logs);
                    break;
            }
        }
    };
    private void SubmitJPushID() {
        Call<CommonResponse> httpResultCall = RetrofitUtils.getRequest(this, false).SubmitJPushID("jpushid", PreferencesUtils.getString(MyApp.getContext(), "userID"), "SD" +PreferencesUtils.getString(RegisterActivity.this,"userID")+jpush);
        httpResultCall.enqueue(new HttpCallBack<CommonResponse>() {
            @Override
            public void onSuccess(Object t) {
            }
            @Override
            public void onFail(int code, String message) {
                if (code == 40104) {
                    SubmitJPushID();
                } else {
                    ToastUtil.getInstance().show(message);
                }
            }
        });
    }

    /**
     * 初始化定位相关代码
     */
    public void initMyLocation() {
        // 定位初始化
        mLocationClient = new LocationClient(getApplicationContext());
        mMyLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(mMyLocationListener);
        // 设置定位的相关配置
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 设置定位模式
        option.setIsNeedAddress(true);//返回的定位结果包含地址信息
        option.setCoorType("bd09ll"); // 设置坐标类型  只适用百度地图  火星坐标系
        mLocationClient.setLocOption(option);
        if (!mLocationClient.isStarted()) {
            mLocationClient.start();
        }
    }

    /**
     * 实现实位回调监听
     */
    private String mCurrentAddress = "";

    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null)
                return;
            /**
             * 最新一次的经纬度
             */
            mCurrentAddress = location.getAddrStr();
            mCurrentLantitude = location.getLatitude();
            mCurrentLongitude = location.getLongitude();
            // 第一次定位时，将地图位置移动到当前位置
            if (isFristLocation) {
                isFristLocation = false;
                if (!TextUtils.isEmpty(mCurrentAddress)) {
                    //mCurrentAddress = mCurrentAddress.substring(2, mCurrentAddress.length());
                    locationModel.setLng(mCurrentLongitude);
                    locationModel.setLat(mCurrentLantitude);
                } else {
                    mCurrentAddress = "暂无位置信息";
                    locationModel.setLng(0d);
                    locationModel.setLat(0d);
                }
                Log.d("locationModel", Tools.javabeanToJson(locationModel));
                getCurrentCity(tv_cityname, mCurrentLantitude, mCurrentLongitude);
            }
        }

    }

    public void getCurrentCity(final TextView tvNowCity, double lat, double lng) {
        Call<AddressModel> httpResultCall = RetrofitUtils.getBaiduRequest().getaddress("json", lat + "," + lng, "8ju0emm7Fj6zV8S0HpKjzAqPdI1YFPGR");
        httpResultCall.enqueue(new Callback<AddressModel>() {
            @Override
            public void onResponse(Call<AddressModel> call, Response<AddressModel> response) {
                AddressModel addressModel = response.body();
                if (addressModel.getResult().getCityCode() == 0) {//百度定位失败
                    tvNowCity.setText("");
                    ToastUtil.getInstance().show("定位失败，请重新定位");
                } else {
                    ToastUtil.getInstance().show("定位成功");
                    tvNowCity.setText(addressModel.getResult().getAddressComponent().getCity());
                }
            }
            @Override
            public void onFailure(Call<AddressModel> call, Throwable t) {
                ToastUtil.getInstance().show("请求失败");
            }
        });
    }//调用百度接口获取城市

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String phone = editPhoneReg.getText().toString().trim();
        String yzm = edit_checknum.getText().toString().trim();
        String pwd = edit_ps.getText().toString().trim();
        String city = tv_cityname.getText().toString().trim();
        if (!TextUtils.isEmpty(phone) && !TextUtils.isEmpty(yzm) && !TextUtils.isEmpty(pwd) && !TextUtils.isEmpty(city)) {
            btn_submit.setClickable(true);
            btn_submit.setBackgroundResource(R.drawable.bg_btn_mainred);
        } else {
            btn_submit.setClickable(false);
            btn_submit.setBackgroundResource(R.drawable.bg_btn_gray);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stop();
        }
        ButterKnife.unbind(this);
    }
}
